#include "stdafx.h"
#include ".\userfactory.h"
#include ".\TempUser.h"
#include ".\User.h"

UserFactory g_UserFactory;


UserFactory::UserFactory()
{
	m_pTempUserPool			= new util::CMemoryPoolFactory<TempUser>;
	m_pUserPool				= new util::CMemoryPoolFactory<User>;
	m_pPlayerKeyGenerator	= new util::CObjKeyGenerator( PLAYER_OBJECT_KEY+1, MONSTER_OBJECT_KEY );
}

UserFactory::~UserFactory()
{
	SAFE_DELETE(m_pTempUserPool);
	SAFE_DELETE(m_pUserPool);
	SAFE_DELETE(m_pPlayerKeyGenerator);
}

VOID UserFactory::ReleaseFactory()
{
	m_pTempUserPool->Release();
	m_pUserPool->Release();
}

VOID UserFactory::InitFactory( DWORD dwUserSIze )
{
	m_pTempUserPool->Initialize( dwUserSIze, dwUserSIze/2+1 );
	m_pUserPool->Initialize( dwUserSIze, dwUserSIze/2+1 );
}

UserSession *	UserFactory::AllocUser( eUSER_TYPE type )
{
	UserSession * pUser = NULL;
	switch( type )
	{
	case UT_TEMP_USER:
		{
			pUser = m_pTempUserPool->Alloc();		
		}
		break;
	case UT_USER:
		{
			pUser = m_pUserPool->Alloc();
			DWORD key = m_pPlayerKeyGenerator->GetKey();
			ASSERT( key != 0 );
			((User*)pUser)->SetPlayerKey( key );
		}
		break;
	}

	pUser->setUserType( type );
	pUser->init();
	return pUser;
}

VOID UserFactory::FreeUser( UserSession * pUser )
{
	pUser->release();
	switch( pUser->getUserType() )
	{
	case UT_TEMP_USER:
		{
			m_pTempUserPool->Free( (TempUser *)pUser );
		}
		break;
	case UT_USER:
		{
			DWORD key = ((User*)pUser)->GetPlayerKey();
			m_pPlayerKeyGenerator->RestoreKey( key );
			m_pUserPool->Free( (User *)pUser );
		}
		break;
	}
}

VOID UserFactory::DisplayPoolInfo()
{
	DISPMSG( "[%4u,%4u][band:%u node:%u] TempUserPool\n", m_pTempUserPool->GetPoolBasicSize(), m_pTempUserPool->GetPoolExtendSize(), 
										m_pTempUserPool->GetNumberOfBands(), m_pTempUserPool->GetAvailableNumberOfTypes() );
	DISPMSG( "[%4u,%4u][band:%u node:%u] UserPool\n", m_pUserPool->GetPoolBasicSize(), m_pUserPool->GetPoolExtendSize(), 
																	m_pUserPool->GetNumberOfBands(), m_pUserPool->GetAvailableNumberOfTypes() );
}
